var UranusWei = angular.module("UranusWei");

/* 单品页 */
UranusWei.controller("productindex", ['$scope', '$rootScope', 'uranusiscroll', 'commonFactory', 'uranusPlus', 'appconfig', '$timeout', '$interval', '$stateParams', 'CacheFactory', '$location', function ($scope, $rootScope, uranusiscroll, commonFactory, uranusPlus, appconfig, $timeout, $interval, $stateParams, CacheFactory, $location) {
    var linkurl=''
    if ($rootScope.previousState && ($rootScope.previousState.url == '/home'||$rootScope.previousState.url == '/list')) {
        linkurl = '/main'+$rootScope.previousState.url;       
    }
    $rootScope.Template = {
        title: '',
        state: 'productindex',
        showbackicon: true,
        showheader: true,
        backlink: linkurl,
        slideopeacity: true,//下拉显示顶部导航的功能 
        opacity: 0
    }
    // commonFactory.setBackLink("/main/list", ["/other/transfercomplete", "/login/index", "/mine/experienceinfo"]);//设置返回连接
    CacheFactory.setStorage('p_producturl', $location.path())
    var dthis = new uranusiscroll();
    uranusiscroll = dthis.init(false, false, true, true);
    var pathName = location.pathname;
    uranusiscroll.scrollMove = function () {
        commonFactory.slideopeacity(uranusiscroll, pathName);
    }
    uranusiscroll.scrollEnd = function () {
        commonFactory.slideopeacity(uranusiscroll, pathName);
    }
    $scope.showtype = 1;//显示的tab
    $scope.isshowbutton = false;//显示购买按钮 
    $scope.submit = {};
    $scope.user = null;//用户信息
    var initposition;
    //优化每次切换选项时
    var js_title = document.querySelector("#js_title");
    if (js_title) {
        initposition = js_title.getBoundingClientRect();
    }
    var productcode = $stateParams.productcode;
    if (!productcode) {
        commonFactory.go('/404');
        return;
    }
    CacheFactory.setStorage('time_comebackUrl', '/product/' + productcode, { isExpires: true, expiresTime: CacheFactory.hour * 1 })//开户成功页面回调地址
    $scope.ShowType = function (type) {
        $scope.showtype = type;
        uranusiscroll.scrollTo(0, 0, 3);
        $timeout(function () {
            uranusiscroll.refresh();
        }, 300);
    }
    var nofocus = document.querySelector('#nofocus')
    nofocus.addEventListener('touchstart', function () {
        commonFactory.inputBlur();
    }, false);
    $scope.ProductInfo = {
        AnnualRateOfYear: 0
    };
    $scope.closelayout = function () {
        commonFactory.messageclose();
    }
    /* 买入 */
    $scope.investbuy = function (id) {
        commonFactory.inputBlur();
        commonFactory.ajax("/api/user/getuserinfo", {}, function (result) {
            if (result.code == 1) {
                if (result.data.userId <= 0) {
                    commonFactory.gologin();
                    return;
                }
                var userinfo = result.data;
                $scope.userinfo = result.data;
                if (!userinfo.usrCustId || userinfo.usrCustId == null) {
                    // commonFactory.go("/mine/realname");
                    commonFactory.ajax("/api/bank/gettime", {}, function (result) {
                        if (result.code == 1) {
                            commonFactory.messageclose();
                            var severseTime = new Date(new Date(result.data.replace(/-/g, '/')).getTime()); //服务器时间
                            var nhours = severseTime.getHours();
                            var nminutus = severseTime.getMinutes();
                            if (nhours >= 1 && nhours <= 5) {
                                var html = '<div id="js_singlePrice">';
                                html += '       <section class="withtan_box">';
                                html += '           <p class="clearfix witht_b_tit">';
                                html += '               <span class="text_center">&nbsp;提示</span>';
                                html += '               <span class="pull-right with_b_t_icon" ng-click="closelayout()"></span>';
                                html += '           </p>';
                                html += '           <div class="withtan_content">';
                                html += '               <div class="clearfix with_c_div" style="padding-bottom:1.0667rem">';
                                html += '                   为了保障用户资金安全，平台1:00--5:00为银行对账时段，暂停汇付天下账户开通，请您稍后操作。感谢您的理解与支持。';
                                html += '               </div>';
                                html += '               <div class="withtan_content_bth with_c_p_but_color" ng-click="closelayout()">';
                                html += '                   我知道了';
                                html += '               </div>';
                                html += '           </div>';
                                html += '       </section>';
                                html += '   </div>';
                                commonFactory.messageview(html, { width: 1, height: 1 }, $scope);
                            } else {
                                commonFactory.go('/mine/realname')
                            }
                        }
                    }, function () { }, 'post')
                    return;
                } else {
                    goBuy();
                }
            } else if (result.code == 8) {
                commonFactory.gologin();
            } else {
                commonFactory.messageshow({ content: "<div class='bg_tan'>获取用户信息失败</div>" });
            }
        }, function () {
            commonFactory.messageshow({ content: "<div class='bg_tan'>获取用户信息失败</div>" });
        }, "post");
        var goBuy = function () {
            if (checkPrice()) {
                //购买
                commonFactory.messageloading();
                // 月月赚投标验证
                commonFactory.ajax("/api/UserProduct/CanInvestProduct", { Price: $scope.submit.shopprice, ProductId: id }, function (result) {
                    commonFactory.messageclose();
                    CacheFactory.setStorage("monthBuyPrice", $scope.submit.shopprice)
                    if (result.code == 1) {
                        commonFactory.go("/month/orderconfirmpayment/" + productcode);
                    } else if (result.code == 8) {
                        commonFactory.gologin();
                    } else {
                        if (result.data) {
                            commonFactory.messageshow({ content: "<div class='bg_tan'>" + result.data + "</div>" });
                        } else {
                            commonFactory.messageshow({ content: "<div class='bg_tan'>购买产品失败，请稍后再试</div>" });
                        }
                    }
                }, function () {
                    commonFactory.messageclose();
                    commonFactory.messageshow({ content: "<div class='bg_tan'>购买产品失败，请稍后再试</div>" });
                }, "post")
            }
        }
    }
    $scope.GetProfit = function (keyup) {
        var shopprice = parseFloat($scope.submit.shopprice);
        if (checkPrice(true) || shopprice >= $scope.ProductInfo.MinBuyPrice) {
            calcProfit();
        } else {
            $scope.profit = null;
        }
    };
    /*计算输入金额的投资收益*/
    function calcProfit() {
        var supPrice = (parseFloat($scope.ProductInfo.LoanPrice) - parseFloat($scope.ProductInfo.CurrentTotalPrice));
        var maxPrice = $scope.ProductInfo.MaxBuyPrice <= 0 ? supPrice : $scope.ProductInfo.MaxBuyPrice > supPrice ? supPrice : $scope.ProductInfo.MaxBuyPrice;
        if ($scope.submit.shopprice > maxPrice) {
            $scope.submit.shopprice = maxPrice;
        }
    }
    /* 检测输入的金额是否符合购买要求 */
    var checkPrice = function (keypress) {
        var submit = $scope.submit;
        submit.shopprice = parseFloat(submit.shopprice);
        if (!submit.shopprice || isNaN(parseFloat(submit.shopprice)) || parseFloat(submit.shopprice) == 0) {
            if (!keypress) {
                commonFactory.messageshow({ content: "<div class='bg_tan'>请输入购买金额</div>" });
            }
            return false;
        }
        if (submit.shopprice % $scope.ProductInfo.minBuyPrice != 0) {
            if (!keypress) {
                commonFactory.messageshow({ content: "<div class='bg_tan'>请输入" + $scope.ProductInfo.minBuyPrice + "的整倍数</div>" });
            }
            return false;
        }
        else if (submit.shopprice < $scope.ProductInfo.minBuyPrice) {
            if (!keypress) {
                commonFactory.messageshow({ content: "<div class='bg_tan'>该产品购买金额最少为" + $scope.ProductInfo.minBuyPrice + "元</div>" });
            }
            submit.shopprice = $scope.ProductInfo.MinBuyPrice
            return false;
        }
        if (!keypress) {
            /* 单笔最大购买金额 */
            if ($scope.ProductInfo.maxBuyPrice > 0 && submit.shopprice > $scope.ProductInfo.maxBuyPrice) {
                commonFactory.messageshow({ content: "<div class='bg_tan'>单笔最多可购买" + $scope.ProductInfo.maxBuyPrice + "元</div>" });
                return false;
            }
        }
        return true;
    };
    var djsproduct;
    /* 设置产品信息的逻辑 */
    function setproductinfo(data) {
        data.productInfo.firstTimeOnlineTime = parseInt(data.productInfo.firstTimeOnlineTime);
        data.serverTime = parseInt(data.serverTime);

        $scope.ServerTime = data.serverTime;//服务器时间
        $scope.loanUserInfo = data.loanUserInfo;//服务器时间
        $scope.ProductInfo = angular.copy(data.productInfo);
        $scope.ProductInfo.productImages = [];
        // //产品倒计时
        // if ($scope.ProductInfo.productStatusID == 3 && $scope.ProductInfo.firstTimeOnlineTime > $scope.ServerTime) {
        //     if ($scope.ServerTime) {
        //         $interval.cancel(djsproduct);
        //     }
        //     $scope.isdaojishi = true;
        //     djsproduct = $interval(function () {
        //         $scope.ServerTime = parseInt($scope.ServerTime) + 1000;
        //         if ($scope.ProductInfo.firstTimeOnlineTime <= $scope.ServerTime) {
        //             $scope.isdaojishi = false;
        //             $interval.cancel(djsproduct);
        //         }
        //     }, 1000);
        // } else {
        //     $scope.isdaojishi = false;
        // }
        $scope.OrderItem = data.orderItem;
        data.loanUserInfo.authInfo = commonFactory.uniqueArr(data.loanUserInfo.authInfo, "PropertySubID");

        $scope.LoanUserInfo = data.loanUserInfo;
        $scope.isshowbutton = true;
        $timeout(function () {
            uranusiscroll.refresh();
        }, 300);
    }

    var initdata = function () {
        commonFactory.messageloading({ process: true });
        $scope.user = CacheFactory.getUser();
        var redis_productinfo = CacheFactory.getStorage("time_productindex_" + productcode);
        if (redis_productinfo) {
            setproductinfo(redis_productinfo);
            commonFactory.messageclose();
        }
        if ($location && $location.$$search) {
            $scope.type = $location.$$search.v;
        }
        // 通过产品id获取产品详情数据
        commonFactory.ajax("/api/UserProduct/GetProductById", { productId: productcode }, function (result) {
            commonFactory.messageclose();
            if (result.code == 1) {
                var data = result.data;
                var productname = data.productInfo.productName;
                if (data.loanUserInfo.idCardUrl && data.loanUserInfo.idCardUrl != "") {
                    if (data.loanUserInfo.idCardUrl.indexOf("http://") == -1 && data.loanUserInfo.idCardUrl.indexOf("https://") == -1) {
                        data.loanUserInfo.idCardUrl = $rootScope.imgbaseurl + data.loanUserInfo.idCardUrl;
                    }
                }
                $rootScope.Template.title = productname.length > 15 ? productname.substr(0, 15) + "..." : productname;
                if (data.ProductDesc) {
                    var srcReg = /src=\"([^\"]*?)\"/gi;
                    var srcRegmatch = data.ProductDesc.match(srcReg);
                    if (srcRegmatch && srcRegmatch.length > 0) {
                        data.ProductDesc = data.productDesc.replace(srcReg, "on-load=\"imgload()\" class='js_layou_photos' src=\"$1\" vg-src=\"'$1'\" style=\"max-width:100%;\"  ");
                        $compile(data.ProductDesc)($scope);/*此处好像有问题，vg-src不加载图*/
                    }
                }

                if (!commonFactory.comparisonobj(result.data, redis_productinfo)) {
                    var lineColor = document.querySelector(".lineColor");
                    if (lineColor) {
                        CurrentWidth = result.data.productInfo.currentSchedule * 100; //百分之几
                        lineColor.style.width = CurrentWidth + "%";//动画width
                    }
                    setproductinfo(result.data);
                    CacheFactory.setStorage("time_productindex_" + productcode, result.data, { isExpires: true, expiresTime: CacheFactory.day * 3 });
                }
                var imgData = result.data.productInfo.productImages.reverse();
                if (imgData.length > 0) {
                    for (var i = imgData.length - 1; i >= 0; i--) {
                        if (imgData[i].inputValue && imgData[i].inputValue != "") {
                            if (imgData[i].inputValue.indexOf("http://") == -1 && imgData[i].inputValue.indexOf("https://") == -1) {
                                imgData[i].inputValue = $rootScope.imgbaseurl + imgData[i].inputValue;
                            }
                        }
                    }
                }
                $scope.ProductInfo.productImages = imgData;
                $timeout(function () {
                    uranusiscroll.refresh();
                    onWndLoad()
                }, 300);
            } else {
                commonFactory.messageclose();
                commonFactory.go("/404");
            }
        }, function () {
            commonFactory.messageclose();
        }, "get");
        var infoimged = 0;
        $scope.imgInfoLoad = function () {
            infoimged++;
            if (infoimged == $scope.ProductInfo.productImages.length) {
                var imgs = document.getElementById("product_photo_show");
                if (imgs) {
                    imgs = imgs.querySelectorAll(".js_layou_photos");
                    commonFactory.messagephotos(imgs, { shadeClose: true }, $scope);
                }
                $timeout(function () {
                    uranusiscroll.refresh();
                }, 250);
            }
        }
    }
    initdata();
    initDataHeTont();

    function initDataHeTont() {
        commonFactory.messageloading({ process: true });
        $scope.user = CacheFactory.getUser();
        if ($scope.ProductInfo.BusinessTypeID == 4) {
            commonFactory.ajax("/api/product/GetHeTongByProductCode", { productcode: productcode }, function (result) {
                commonFactory.messageclose();
                if (result.code == 1) {
                    var data = result.data;
                    $scope.menulist = data;
                } else {
                    commonFactory.messageclose();
                    commonFactory.messageshow({ content: "<div class='bg_tan'>该产品合同不存在</div>", time: 2 });
                    $timeout(function () {
                        commonFactory.go('back');
                    }, 2000);
                }
            }, function () {
                commonFactory.messageclose();
            }, "post");
        }

        var loadimgcount = 0;
        $scope.imgload = function () {
            loadimgcount++;
            var imgs = document.getElementById("product_photo_show");
            if (imgs) {
                imgs = imgs.querySelectorAll(".js_layou_photos");
            }
            if (loadimgcount >= imgs.length) {
                $timeout(function () {
                    commonFactory.messagephotos(imgs, { shadeClose: true }, $scope);
                }, 200);
            }

            $timeout(function () {
                uranusiscroll.refresh();
            }, 250);
        }
    }

}]);
/* 合同页 */
UranusWei.controller("productcp", ['$scope', '$rootScope', 'uranusiscroll', 'commonFactory', 'uranusPlus', 'appconfig', '$timeout', '$interval', '$stateParams', 'CacheFactory', '$location', function ($scope, $rootScope, uranusiscroll, commonFactory, uranusPlus, appconfig, $timeout, $interval, $stateParams, CacheFactory, $location) {
    if (window.location.pathname == "/product/contract") {
        titleName = "定向委托投资协议"
    } else {
        titleName = "债权转让协议"
    }
    $rootScope.Template = {
        title: titleName,
        state: 'contract',
        showbackicon: true,
        showheader: true,
        slideopeacity: true,//下拉显示顶部导航的功能 
    }
    var dthis = new uranusiscroll();
    var text = commonFactory.GetRandomPullAd();
    dthis.showtext({ downtext: text, opentext: text, loadingtext: text });
    uranusiscroll = dthis.init(true);
    uranusiscroll.pullDownAction = function () {
        text = commonFactory.GetRandomPullAd();
        dthis.showtext({ downtext: text, opentext: text, loadingtext: text });
        $timeout(function () {
            uranusiscroll.refresh();
        }, appconfig.pulldowntime);
    }

    $scope.oMyId = CacheFactory.getStorage('contractId');
    $scope.DqInvestmentInfoTab = $scope.oMyId.repaymentItemFormDtos
    commonFactory.ajax("/api/Product/GetUserConstract", { id: $scope.oMyId.userContractId }, function (result) {//定期项目详情合同
        $scope.GetUserContractByOrderItemId = result.data;
        $scope.tabInDate = $scope.GetUserContractByOrderItemId.createTime.substring(0, 10).replace(/\-/g, '.');//2017.06.22
        var arr = $scope.GetUserContractByOrderItemId.createTime.substring(0, 10).split(/\-/g);//2017年10月22日
        $scope.beginDate = arr[0] + '年' + arr[1] + '月' + arr[2] + '日';
    }, null, 'post')
    $scope.initDatas = function (last) {
        if (last) {
            $timeout(function () {
                uranusiscroll.refresh();
            }, 200);
        }
    }
}]);
/* 订单确认页 */
UranusWei.controller("orderconfirmpayment", ['$scope', '$rootScope', 'uranusiscroll', 'commonFactory', 'appconfig', '$timeout', '$interval', '$stateParams', 'CacheFactory', '$location', function ($scope, $rootScope, uranusiscroll, commonFactory, appconfig, $timeout, $interval, $stateParams, CacheFactory, $location) {
    $rootScope.Template = {
        title: '订单确认',
        state: 'orderconfirmpayment',
        showbackicon: true,
        showheader: true,
        backlink: ''
    }
    var dthis = new uranusiscroll();
    var text = commonFactory.GetRandomPullAd();
    dthis.showtext({ downtext: text, opentext: text, loadingtext: text });
    uranusiscroll = dthis.init(true, false, false, true);
    uranusiscroll.pullDownAction = function () {
        text = commonFactory.GetRandomPullAd();
        dthis.showtext({ downtext: text, opentext: text, loadingtext: text });
        $timeout(function () {
            uranusiscroll.refresh();
        }, appconfig.pulldowntime);
    }
    $scope.monthBuyPrice = 0;      //支付金额
    $scope.GetCanUserPlusInterest = 0;
    $scope.orderinfoplus = {
        agreeprotocol: true/* 用户协议 */
    };
    var initdata = function () {
        commonFactory.messageloading({ process: true });
        var loadingArr = [], loadingCount = 2;
        commonFactory.initComplate(loadingArr, loadingCount, function () {
            commonFactory.messageclose();
        });

        var id = $stateParams.id;
        $scope.goback = function (e) {
            commonFactory.go('/product/'+id)//处理订单页面回退到汇付天下问题
        }
        CacheFactory.setStorage('time_comebackUrl', '/month/orderconfirmpayment/' + id, { isExpires: true, expiresTime: CacheFactory.hour * 1 })//快捷充值回调地址
        if (id) {
            // 加息券
            //计算请求ajax
            function jxqAjax() {
                commonFactory.ajax("/api/UserProduct/CalcInterest",
                    { ProductId: id, Price: $scope.monthBuyPrice, PlusInterestId: $scope.jxqId },
                    function (result) {
                        if (result.code == 1) {
                            $scope.GetInterest = result.data;
                            CacheFactory.setStorage("GetPlusInterest", result.data);
                        } else if (result.code == 2) {
                            commonFactory.messageshow({ content: "<div class='bg_tan'>" + result.data + "</div>", index: 1000 });
                        } else if (result.code == 4) {
                            commonFactory.messageshow({ content: "<div class='bg_tan'>" + result.data + "</div>", index: 1000 });
                        } else if (result.code == 110) {
                            commonFactory.messageshow({ content: "<div class='bg_tan'>" + result.data + "</div>", index: 1000 });
                        }
                    }, null, "post");
            }
            $scope.monthBuyPrice = CacheFactory.getStorage("monthBuyPrice");// 购买金额
            // 解决android（第一次读取不到缓存）读取缓存慢的问题
            if (!$scope.monthBuyPrice) {
                var getcount = 0;
                var priceInterval = $interval(function () {
                    $scope.monthBuyPrice = CacheFactory.getStorage("monthBuyPrice");// 购买金额
                    getcount++;
                    if ($scope.monthBuyPrice || getcount > 10) {
                        $interval.cancel(priceInterval);
                        jxqAjax();
                    }
                }, 50)
            } else {
                jxqAjax()
            }
            var time_mineprice = CacheFactory.getStorage("time_mineprice")
            if (time_mineprice) {
                $scope.userinfo = time_mineprice
                $scope.userinfo.UsablePrice = time_mineprice.usableCash;
            }
            commonFactory.ajax("/api/price/myprice", {}, function (result) {
                if (result.code == 1) {
                    $scope.userinfo = result.data;
                    $scope.myprice = result.data;
                    $scope.userinfo.UsablePrice = result.data.usableCash;
                    if ($scope.userinfo.usableAmount < $scope.monthBuyPrice) {//余额不足 弹出框去充值绑定值
                        $scope.reduce = $scope.monthBuyPrice - $scope.userinfo.usableAmount ;
                        CacheFactory.setStorage("chargeprice", $scope.reduce)//设置充值成功页面显示金额缓存
                    }
                    CacheFactory.setStorage("time_mineprice", result.data, { isExpires: true, expiresTime: CacheFactory.day * 1 });
                }
            }, function () {
                commonFactory.messageshow({ content: "<div class='bg_tan'></div>" });
            }, "post");
            $scope.showLayer = function (type) {//加息弹框 
                if (type == 1) {
                    var js_jxq = document.querySelector('#js_jxq');
                    js_jxq.style.display = 'block';
                    var checkI = js_jxq.getElementsByTagName('i')
                    cache_getId = CacheFactory.getStorage("getWeal");
                    if (cache_getId && cache_getId.data != '') {
                        for (j = 0; j < checkI.length; j++) {
                            if (checkI[j].getAttribute("name") == cache_getId.id) {
                                checkI[j].className = 'true_checked o_checked pull-left';
                            }
                        }
                    } else {
                        checkI[0].className = '';
                    }
                } else if (type == 2) {
                    commonFactory.messageshow({ content: "<div class='bg_tan'>您暂无可用加息券哦!</div>" });
                }
            }

            $scope.arguments = function (obj, $event) {//点击关闭 向页面传入加息额度
                var js_jxq = document.querySelector('#js_jxq');
                if (js_jxq && js_jxq.style.display == "block") {
                    js_jxq.style.display = 'none';
                }
                if (obj == 1) {
                    $scope.jxqNum = '未使用加息券';
                    $scope.bindNum = false;
                    $scope.jxqId = '';
                    CacheFactory.setStorage('getWeal', "")//给缓存重新赋值
                    var js_checked = js_jxq.getElementsByTagName('i');  //单选第一个li
                    for (i = 0; i < js_checked.length; i++) {
                        if (js_checked[0]) {
                            js_checked[0].className = ''
                        }
                        js_checked[i].className = 'false_checked o_checked pull-left'
                    }
                    var ele = $event.target;
                    while (ele.tagName != 'LI') {
                        ele = ele.parentNode;
                    }
                    ele.getElementsByTagName('i')[0].className = '';
                    jxqAjax()
                }
                if (obj && obj != 1) {
                    if (CacheFactory.getStorage("getWeal")) {
                        CacheFactory.setStorage('getWeal', obj)//给缓存重新赋值
                    }
                    var js_checked = js_jxq.getElementsByTagName('i');  //单选
                    for (i = 0; i < js_checked.length; i++) {
                        if (js_checked[0]) {
                            js_checked[0].className = ''
                        }
                        js_checked[i].className = 'false_checked o_checked pull-left'
                    }
                    var ele = $event.target;
                    while (ele.tagName != 'LI') {
                        ele = ele.parentNode;
                    }
                    ele.getElementsByTagName('i')[0].className = 'true_checked o_checked pull-left';
                    $scope.bindNum = obj.interestRate
                    $scope.jxqNum = '+' + obj.interestRate + '%加息券'
                    $scope.jxqId = obj.id;
                    jxqAjax();
                }
            }
            commonFactory.ajax("/api/UserProduct/GetProductById", { productId: id }, function (result) {
                loadingArr.push("getorderconfirmpayment");
                if (result.code == 1) {
                    var data = result.data.productInfo;
                    $scope.orderinfo = data;
                    CacheFactory.setStorage("user_transactioninfo", data, { isExpires: true, expiresTime: CacheFactory.min * 20 });
                    commonFactory.ajax("/api/product/GetCanUserPlusInterest", {}, function (result) { //放到这里是为了判断是否为新手标
                        if (result.code == 1) {
                            $scope.GetCanUserPlusInterest = result.data;
                            cache_getwlist = CacheFactory.getStorage("getWeal");//获取加息券页面参数缓存;
                            if (cache_getwlist && cache_getwlist.data != '' && $scope.orderinfo.productGroupId != 1 && $scope.orderinfo.productGroupId != 9) { //跨页面传参 判断参数
                                $scope.GetCanUserPlusInterest.forEach(function (item) {
                                    if (item.id == cache_getwlist.id) {
                                        $scope.bindNum = cache_getwlist.interestRate;
                                        $scope.jxqNum = '+' + cache_getwlist.interestRate + '%加息券' //默认选中加息券列表页选中的加息券
                                        $scope.jxqId = cache_getwlist.id;
                                        // 计算预期收益额
                                        jxqAjax();
                                    }
                                })
                            } else {
                                $scope.jxqNum = '未使用加息券';//默认
                                $scope.jxqId = '';
                                // 计算预期收益额
                                jxqAjax()
                            }
                        }
                    }, function () { }, "post");

                } else if (result.code == 8) {
                    commonFactory.gologin();
                    // } else if (result.code == 110) {
                    //     commonFactory.messageshow({ content: "<div class='bg_tan'>交易不存在，即将跳转</div>" });
                    //     $timeout(function () {
                    //         commonFactory.go("/main/list");
                    //     }, 250);
                } else {
                    commonFactory.messageshow({ content: "<div class='bg_tan'>获取订单失败，即将跳转</div>" });
                    $timeout(function () {
                        commonFactory.go("/main/list");
                    }, 1500);
                }
            }, function () {
                loadingArr.push("getorderconfirmpayment");
                commonFactory.messageshow({ content: "<div class='bg_tan'>获取订单失败，即将跳转</div>" });
                $timeout(function () {
                    commonFactory.go("/main/list");
                }, 1500);
            }, "get");
            // 获取银行卡限额
            function getbankinfo() {
                var banklimitList = CacheFactory.getStorage("banklimitList");
                if (banklimitList && banklimitList.length > 0) {
                    banklimitList.forEach(function (obj) {
                        if (obj.bankCode && $scope.getuserinfo.bankCode) {
                            if (obj.bankCode.toLowerCase() == $scope.getuserinfo.bankCode.toLowerCase()) {
                                $scope.bankInfo = obj;
                                $scope.bankInfo.bankIcon = $rootScope.imgbaseurl + $scope.bankInfo.bankCode + '.png'
                            }
                        }
                    })
                }
                // 银行卡限额列表接口
                commonFactory.ajax("/api/bank/GetBankLimitList", {}, function (result) {
                    if (result.code == 1) {
                        CacheFactory.setStorage("banklimitList", result.data);
                        if (result.data.length > 0) {
                            result.data.forEach(function (obj) {
                                if (obj.bankCode && $scope.getuserinfo.bankCode) {
                                    if (obj.bankCode.toLowerCase() == $scope.getuserinfo.bankCode.toLowerCase()) {
                                        $scope.bankInfo = obj;
                                        $scope.bankInfo.bankIcon = $rootScope.imgbaseurl + $scope.bankInfo.bankCode + '.png'
                                    }
                                }
                            })
                        }
                    }
                }, function () {
                    commonFactory.messageshow({ content: "<div class='bg_tan'>获取银行限额表失败</div>" });
                }, "post");

            }
            //获取用户绑定的银行卡
            var cache_bankinfo = CacheFactory.getStorage("user_bankinfo");
            if (cache_bankinfo) {
                getbankinfo();
                loadingArr.push("GetUserBankInfo");
            }
            commonFactory.ajax("/api/user/getuserinfo", {}, function (result) {
                if (!cache_bankinfo) {
                    loadingArr.push("GetUserBankInfo");
                }
                if (result.code == 1) {
                    if (result.data.userId <= 0) {
                        commonFactory.gologin();
                        return;
                    }
                    var data = result.data;
                    $scope.getuserinfo = data
                    if (data.bankCard) {
                        getbankinfo();
                    } else {
                        //没有银行卡
                    }
                    $timeout(function () {
                        uranusiscroll.refresh();
                    }, 300);
                } else if (result.code == 8) {
                    commonFactory.gologin();
                } else {
                    commonFactory.messageshow({ content: "<div class='bg_tan'>获取银行卡信息失败</div>" });
                }
            }, function () {
                if (!cache_bankinfo) {
                    loadingArr.push("GetUserBankInfo");
                }
                $timeout(function () {
                    uranusiscroll.refresh();
                }, 300);
                commonFactory.messageshow({ content: "<div class='bg_tan'>获取银行卡信息失败</div>" });
            }, "post");
        } else {
            commonFactory.go("back");
        }
    }
    var gid = $stateParams.id
    $scope.djstime = 60;
    /* 去支付 */
    $scope.gopay = function () {
        commonFactory.messageclose();
        if (!$scope.orderinfoplus.agreeprotocol) {
            commonFactory.messageshow("<div class='bg_tan'>请先同意相关协议、风险提示函及免责声明</div>");
            return;
        }
        if ($scope.getuserinfo.bankCode && $scope.bankInfo.singlePrice < $scope.reduce) {//充值金额大于银行限额弹框
            var js_fastpay = document.querySelector("#js_singlePrice");
            if (js_fastpay) {
                var html = js_fastpay.innerHTML;
                commonFactory.messageview(html, { height: 1, width: 1, shadeClose: true }, $scope);
            }
            return;
        } else if ($scope.userinfo.usableAmount < $scope.monthBuyPrice) {//去充值弹框
            var js_fastpay = document.querySelector("#js_recharge");
            if (js_fastpay) {
                var html = js_fastpay.innerHTML;
                commonFactory.messageview(html, { height: 1, width: 1, shadeClose: true }, $scope);
            }
            return;
        } else {
            var js_safepay = document.getElementById("js_safepay");
            var html = js_safepay.innerHTML;
            commonFactory.messageview(html, { height: 1, width: 1 }, $scope);
        }
    }

    /*关闭弹层*/
    $scope.closelayout = function () {
        commonFactory.messageclose();
    }
    /*确认支付*/
    // 充值提交信息
    $scope.rechargeData = {
        RetUrl: "",
        PageType: '2',
        GateBusiId: "QP",
        TransAmt: "",
        OpenBankId: ''
    }


    $scope.enterpay = function (type) {
        if (type == 1) {
            commonFactory.messageloading({ index: 2000, time: 1000 * 60 * 10 });
            //直接支付
            var _jxqId = $scope.jxqId;
            if ($scope.GetCanUserPlusInterest.length > 0) {
                for (i = 0; i < $scope.GetCanUserPlusInterest.length; i++) {
                    if ($scope.GetCanUserPlusInterest[i].id == _jxqId) {
                        $scope.jxqId = _jxqId
                        break;
                    } else {
                        $scope.jxqId = ""
                    }
                }
            } else {
                $scope.jxqId = ""
            }
            commonFactory.ajax("/api/UserProduct/InvestProduct", { ProductId: $stateParams.id, Price: $scope.monthBuyPrice, PlusInterestId: $scope.jxqId, RetUrl: appconfig.baseurladd + '/other/waitting?type=bid', PageType: '2' }, function (result) {
                if (result.code == 1) {
                    $scope.InvestProduct = result.data
                    commonFactory.ajax("/api/UserProduct/GetOrderId", { orderCode: result.data.ordId }, function (result) {
                        if (result.data) {
                            CacheFactory.setStorage("time_queryresult", result.data, { isExpires: true, expiresTime: CacheFactory.hour * 1 });//订单编号
                            var formObject = document.querySelector('#rechargeform')
                            formObject.action = appconfig.hfurl;
                            $scope.ajaxdata = $scope.InvestProduct;
                            $timeout(function () {
                                formObject.submit();
                            }, 50)
                        }
                    }, function () {

                    }, "get");
                    CacheFactory.setStorage('getWeal', '');
                } else if (result.code == 8) {
                    commonFactory.gologin();
                } else {
                    commonFactory.messageclose();
                    if (result.data) {
                        commonFactory.messageshow({ content: "<div class='bg_tan'>" + result.data + "</div>" });
                    } else {
                        commonFactory.messageshow({ content: "<div class='bg_tan'>支付失败，请稍后再试！</div>" });
                    }
                }
            }, function () {
                commonFactory.messageclose();
                commonFactory.messageshow({ content: "<div class='bg_tan'>支付失败，请稍后再试！</div>" });
            }, "post");
        } else if (type == 2) { //快捷支付
            commonFactory.messageclose();
            // 充值确认
            $scope.rechargeData.RetUrl = appconfig.baseurladd + '/other/waitting?type=rechargeon';
            $scope.rechargeData.TransAmt = ($scope.monthBuyPrice - $scope.userinfo.usableAmount).toFixed(2);
            commonFactory.ajax("/api/Account/Recharge", $scope.rechargeData, function (result) {
                if(result.code==2){
                    var js_fastpay = document.querySelector("#js_banrecharge");
                    if (js_fastpay) {
                        var html = js_fastpay.innerHTML;
                        commonFactory.messageview(html, { height: 1, width: 1, shadeClose: true }, $scope);
                    }
                }else{
                    CacheFactory.setStorage("time_queryresult", result.merPriv, { isExpires: true, expiresTime: CacheFactory.min * 30 });
                    var formObject = document.querySelector('#rechargeform')
                    formObject.action = appconfig.hfurl;
                    $scope.ajaxdata = result;
                    $timeout(function () {
                        formObject.submit();
                    }, 50)
                }
            }, function () {
                commonFactory.messageshow({ content: "<div class='bg_tan'>后台请求错误</div>" });
            }, "post");
        }

    }
    initdata();
}]);
